package com.online.fund.spider;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.Resource;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.online.fund.spider.dao.FundDao;
import com.online.fund.spider.entity.SharesTransaction;
import com.online.fund.util.DateUtils;
import com.online.fund.util.HttpClientUtil;

import jdk.nashorn.api.scripting.ScriptObjectMirror;

/**
 * 股票当天交易数据
 * 
 * @author galen.zhang
 *
 */
@Service
@SuppressWarnings("restriction")
public class SharesDailyTransactionProcesser {
	
	private final static Logger logger = LoggerFactory.getLogger(SharesDailyTransactionProcesser.class);
	
	private ExecutorService pool = Executors.newFixedThreadPool(20);

	@Resource
	private FundDao fundDao;

	private final static String SHARES_TRANSACTION_PAGE_URL = "http://nufm.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?type=CT&cmd=#{sharesTypeCode}&sty=FCOIATA&sortType=C&sortRule=-1&page=1&pageSize=#{pageSize}&js=var%20quote_123%3d%7brank:[(x)],pages:(pc)%7d&token=7bc05d0d4c3c22ef9fca8c2a912d779c&jsName=quote_123&_g=0.4888505715865281";

	private static Map<String, String> SHARES_TYPE_MAP = new HashMap<String, String>();

	static {
		SHARES_TYPE_MAP.put("C.2", "上证A股");
		SHARES_TYPE_MAP.put("C.3", "上证B股");
		SHARES_TYPE_MAP.put("C._SZAME", "深证A股");
		SHARES_TYPE_MAP.put("C.7", "深证B股");
	}

	public void parsePage() {
		try {
			for (Entry<String, String> entry : SHARES_TYPE_MAP.entrySet()) {
				pool.execute(() -> {
					try {
						parsePage(entry.getKey(), entry.getValue(), true);
					} catch (Exception e) {
						logger.error("---股票当天交易数据" + entry.getValue(), e);
					}
				});
			}
			
			pool.shutdown();
			while (!pool.isTerminated()) {
				Thread.sleep(1000);
			}
			HttpClientUtil.closeConnectionPool();
		} catch (Exception e) {
			logger.error(e.getMessage());
		}	
	}

	public void parsePage(String sharesTypeCode, String sharesTypeName, boolean saveFlag) {

		try {
			String crawlDate = DateUtils.getCurrentDate();
			String pageSize = "20";
			if (saveFlag) {
				pageSize = "2500";
			}

			String resultStr = HttpClientUtil.httpGetRequest(SHARES_TRANSACTION_PAGE_URL
					.replace("#{sharesTypeCode}", sharesTypeCode).replace("#{pageSize}", pageSize), 5);

			ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
			ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");

			nashorn.eval(resultStr);
			ScriptObjectMirror db = (ScriptObjectMirror) nashorn.get("quote_123");
			ScriptObjectMirror datas = (ScriptObjectMirror) db.get("rank");
			if (datas.isArray()) {
				
				List<SharesTransaction> sharesTransactionList = new ArrayList<SharesTransaction>();
				
				// 删除数据
				if (saveFlag) {
					fundDao.deleteSharesTransaction(crawlDate, sharesTypeCode);
				}
				
				for (int i = 0; i < datas.size(); i++) {
					String data = (String) datas.get("" + i);
					String[] dataArr = data.split(",");
					
					SharesTransaction entity = new SharesTransaction();
					entity.setCrawlDate(crawlDate);
					entity.setSharesTypeCode(sharesTypeCode);
					entity.setSharesTypeName(sharesTypeName);
					entity.setSharesCode(dataArr[1]);
					entity.setSharesName(dataArr[2]);
					if (!dataArr[3].contains("-")) {
						entity.setLatestPrice(Double.parseDouble(dataArr[3]));
					}
					
					if (!dataArr[4].contains("-")) {
						entity.setChangeAmount(Double.parseDouble(dataArr[4]));
					}
					
					if (!dataArr[5].contains("-")) {
						entity.setRiseFallRate(Double.parseDouble(dataArr[5].replace("%", "")));
					}
					
					if (!dataArr[6].contains("-")) {
						entity.setAmplitude(Double.parseDouble(dataArr[6].replace("%", "")));
					}
					
					if (!dataArr[7].contains("-")) {
						entity.setTradingVolume(Double.parseDouble(dataArr[7]));
					}
					
					if (!dataArr[8].contains("-")) {
						entity.setTradingVolumeAmount(Double.parseDouble(dataArr[8]));
					}
					
					entity.setPreviousClosePrice(Double.parseDouble(dataArr[9]));
					if (!dataArr[10].contains("-")) {
						entity.setTodayOpenPrice(Double.parseDouble(dataArr[10]));
					}
					
					if (!dataArr[11].contains("-")) {
						entity.setMaxPrice(Double.parseDouble(dataArr[11]));
					}
					
					if (!dataArr[12].contains("-")) {
						entity.setMinPrice(Double.parseDouble(dataArr[12]));
					}
					
					sharesTransactionList.add(entity);
					
					if (saveFlag) {
						if (i + 1 % 100 == 0) {
							fundDao.batchAddSharesTransaction(sharesTransactionList);
							sharesTransactionList.clear();
						}
					} else {
						System.out.println(data);
						System.out.println(entity);
					}
					
				}
				
				if (saveFlag && !sharesTransactionList.isEmpty()) {
					fundDao.batchAddSharesTransaction(sharesTransactionList);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void main(String[] args) throws Exception {
		SharesDailyTransactionProcesser processer = new SharesDailyTransactionProcesser();
		processer.parsePage("C.2", "上证A股", false);
		
		processer.pool.shutdown();
		while (!processer.pool.isTerminated()) {
			Thread.sleep(1000);
		}
		HttpClientUtil.closeConnectionPool();
	}
}
